package com.yuanda.wordhot.repository;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * 
 * @author YuBai
 * @since 2013-3-18
 * @Description hibernate通用的操作类
 * @version 1.0
 */
public class HibernateGenericDAO<T> implements IRepository<T> {
	protected Class<T> persistClass;
	@Autowired(required = true)
	protected SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	public HibernateGenericDAO() {
		Type genType = this.getClass().getGenericSuperclass();
		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
		this.persistClass = (Class<T>) params[0];
	}

	@SuppressWarnings("unchecked")
	@Override
	public T get(Serializable id) {
		return (T) sessionFactory.getCurrentSession().get(persistClass, id);
	}

	@Override
	public void add(T entity) {
		sessionFactory.getCurrentSession().save(entity);
	}

	@Override
	public void remove(T entity) {
		sessionFactory.getCurrentSession().delete(entity);
	}

	@Override
	public void update(T entity) {
		sessionFactory.getCurrentSession().update(entity);
	}

}
